package com.boyinet.activation.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.boyinet.activation.entity.User;
import com.boyinet.activation.service.UserService;
import com.boyinet.activation.util.R;
import com.boyinet.activation.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lengchunyun
 * @since 2021-01-22
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/current")
    public R current() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.getUserByName(name);
        user.setPassword(null);
        return R.ok().put("data", user);
    }

    @GetMapping("/{id}")
    public R get(@PathVariable("id") String userId) {
        User user = userService.getById(userId);
        return R.ok().put("data", user);
    }

    @PostMapping("/{id}")
    public R update(@PathVariable("id") String userId, @RequestBody User user) {
        userService.saveOrUpdate(user);
        return R.ok("更新成功");
    }

    @PostMapping("/list")
    public R list(@RequestBody UserVO condition) {
        IPage<User> userPage = userService.listByPage(condition);
        Map<String, Object> map = new HashMap<>(4);
        map.put("count", userPage.getTotal());
        map.put("pi", condition.getPage());
        map.put("ps", condition.getLimit());
        map.put("data", userPage.getRecords());
        return R.ok(map);
    }

    @PutMapping()
    public R put(@RequestBody User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.save(user);
        return R.ok();
    }

    public R unlock(@RequestBody User user) {
        Boolean success = userService.unlock(user);
        return success ? R.ok() : R.error();
    }
}

